using System.Collections.Generic;
using System.Linq;
using Common.NotifyEvent;

namespace ProjectView.Windows
{
	public class Node : NotifyPropertyChanged
	{
		private int _ParentId = -1;

		private bool? _IsReadOnly = false;

		private string _Name = "";

		private bool isCheckParent = true;

		private bool isCheckChild = true;

		public List<Node> Children { get; set; }

		public Node Parent { get; set; }

		public int ID { get; set; }

		public int ParentId
		{
			get
			{
				return _ParentId;
			}
			set
			{
				_ParentId = value;
			}
		}

		public bool? IsReadOnly
		{
			get
			{
				return _IsReadOnly;
			}
			set
			{
				_IsReadOnly = value;
				OnPropertyChanged("IsReadOnly");
				if (isCheckChild)
				{
					foreach (Node child in Children)
					{
						child.isCheckParent = false;
						child.IsReadOnly = value;
						child.isCheckParent = true;
					}
				}
				if (Parent == null || !isCheckParent)
				{
					return;
				}
				IEnumerable<Node> enumerable = Parent.Children.Where((Node nodes) => nodes.ParentId == ParentId);
				int num = 0;
				foreach (Node item in enumerable)
				{
					num += ((item.IsReadOnly == true) ? 1 : 0);
				}
				Parent.isCheckChild = false;
				if (Parent.Parent != null)
				{
					if (num > 0)
					{
						Parent.IsReadOnly = true;
					}
					else if (num == 0)
					{
						Parent.IsReadOnly = false;
					}
				}
				else if (num == enumerable.Count())
				{
					if (UnCheckedNodes(Parent) == 0)
					{
						Parent.IsReadOnly = true;
					}
					else
					{
						Parent.IsReadOnly = false;
					}
				}
				else
				{
					Parent.IsReadOnly = false;
				}
				Parent.isCheckChild = true;
			}
		}

		public string Name
		{
			get
			{
				return _Name;
			}
			set
			{
				_Name = value;
				OnPropertyChanged("Name");
			}
		}

		private int UnCheckedNodes(Node tn)
		{
			int num = 0;
			foreach (Node child in tn.Children)
			{
				if (child.IsReadOnly == false)
				{
					num++;
				}
				num += UnCheckedNodes(child);
			}
			return num;
		}

		public Node()
		{
			Children = new List<Node>();
		}

		public void AddChild(Node node)
		{
			Children.Add(node);
			node.Parent = this;
		}
	}
}
